<template>
  <div class="login-page">
    <div class="login-container">
      <div class="login-panel">
        <el-form
          v-if="!isRegister"
          ref="loginForm"
          :model="loginForm"
          :rules="loginRules"
          class="login-form"
          autocomplete="on"
          label-position="left"
        >
          <div class="title-container">
            <h3 class="title"> 欢迎使用开放创新平台 </h3>
          </div>

          <el-form-item class="el-menu-item" prop="username">
            <div class="svg-container">
              <i class="el-icon-user"></i>
              <el-input
                ref="username"
                v-model.trim="loginForm.username"
                placeholder="请输入账号"
                name="username"
                type="text"
                tabindex="1"
                autocomplete="on"
              />
            </div>
          </el-form-item>

          <el-form-item class="el-menu-item" prop="password">
            <div class="svg-container">
              <i class="el-icon-mobile"></i>
              <el-input
                :key="passwordType"
                ref="password"
                v-model="loginForm.password"
                :type="passwordType"
                placeholder="请输入密码"
                name="password"
                tabindex="2"
                autocomplete="on"
                @keyup.native="checkCapslock"
                @blur="capsTooltip = false"
                @keyup.enter.native="handleLogin"
              />
              <span class="show-pwd" @click="showPwd">
                <svg-icon
                  :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'"
                />
              </span>
            </div>
          </el-form-item>

          <el-row style="width: 100%;" :gutter="20">
            <el-col :span="12">
                <el-button
                style="width: 100%;"
                :loading="loading"
                type="primary"
                class="login-btn"
                @click.native.prevent="handleLogin"
                >登陆
              </el-button>
            </el-col>
            <el-col :span="12">
              <el-button
                style="width: 100%;"
                :loading="loading"
                type="primary"
                class="login-btn"
                @click.native.prevent="switchRegister"
                >去注册
              </el-button>
            </el-col>
          </el-row>

        

        </el-form>

        <!-- 注册 -->
        <div v-if="isRegister">
          <el-form
          ref="registerForm"
          :model="registerForm"
          :rules="registerRules"
          class="login-form"
          autocomplete="on"
          label-position="left"
        >
          <div class="title-container">
            <h3 class="title"> 欢迎使用开放创新平台 </h3>
          </div>

          <el-form-item class="el-menu-item" prop="username">
            <div class="svg-container">
              <i class="el-icon-user"></i>
              <el-input
                ref="username"
                v-model.trim="registerForm.username"
                placeholder="请输入用户名"
                name="username"
                type="text"
                tabindex="1"
                autocomplete="on"
              />
            </div>
          </el-form-item>

          <el-form-item class="el-menu-item" prop="password">
            <div class="svg-container">
              <i class="el-icon-mobile"></i>
              <el-input
                :key="passwordType"
                ref="registerPassword"
                v-model="registerForm.password"
                :type="passwordType"
                placeholder="请输入密码"
                name="password"
                tabindex="2"
                autocomplete="on"
                @keyup.native="checkCapslock"
                @blur="capsTooltip = false"
                @keyup.enter.native="handleRegister"
              />
              <span class="show-pwd" @click="showPwd">
                <svg-icon
                  :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'"
                />
              </span>
            </div>
          </el-form-item>

          <el-form-item class="el-menu-item" prop="confirmPassword">
            <div class="svg-container">
              <i class="el-icon-mobile"></i>
              <el-input
                :key="passwordType"
                ref="registerConfirmPassword"
                v-model="registerForm.confirmPassword"
                :type="passwordType"
                placeholder="请再次输入密码"
                name="registerPassword"
                tabindex="2"
                autocomplete="on"
                @keyup.native="checkCapslock"
                @blur="capsTooltip = false"
                @keyup.enter.native="handleRegister"
              />
              <span class="show-pwd" @click="showPwd">
                <svg-icon
                  :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'"
                />
              </span>
            </div>
          </el-form-item>

          <el-form-item class="el-menu-item" prop="username">
            <div class="svg-container">
              <i class="el-icon-message"></i>
              <el-input
                ref="email"
                v-model.trim="registerForm.email"
                placeholder="请输入邮箱"
                name="username"
                type="text"
                tabindex="1"
                autocomplete="on"
              />
              <el-button type="primary" @click="sendEmail">发送验证码</el-button>
            </div>
          </el-form-item>

          <el-form-item class="el-menu-item" prop="code">
            <div class="svg-container">
              <i class="el-icon-mobile"></i>
              <el-input
                :key="passwordType"
                ref="registerConfirmPassword"
                v-model="registerForm.code"
                :type="text"
                placeholder="请输入验证码"
                name="code"
                tabindex="2"
                autocomplete="on"
                @keyup.native="checkCapslock"
                @blur="capsTooltip = false"
                @keyup.enter.native="handleRegister"
              />
              <span class="show-pwd" @click="showPwd">
                <svg-icon
                  :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'"
                />
              </span>
            </div>
          </el-form-item>

          <el-row style="width: 100%;" :gutter="20">
            <el-col :span="12">
                <el-button
                style="width: 100%;"
                :loading="loading"
                type="primary"
                class="login-btn"
                @click.native.prevent="switchLogin"
                >返回登陆
              </el-button>
            </el-col>
            <el-col :span="12">
              <el-button
                style="width: 100%;"
                :loading="loading"
                type="primary"
                class="login-btn"
                @click.native.prevent="handleRegister"
                >注册
              </el-button>
            </el-col>
          </el-row>

        

        </el-form>
        </div>
      </div>
    </div>
    <div class="footer">
      <span class="copyright">开放创新平台</span>
    </div>
  </div>
</template>

<script>
import { loginPageTitle } from "@/settings";
import { login, saveToken} from "@/api/auth";
import { PostRequest } from "@/api/api";

export default {
  name: "Login",
  components: {},
  data() {
    const validateUsername = (rule, value, callback) => {
      if (value.length < 2) {
        callback(new Error("请输入正确的账号"));
      } else {
        callback();
      }

     
    };
    const validatePassword = (rule, value, callback) => {
      if (value.length < 3) {
        callback(new Error("密码字符个数不能小于3位"));
      } else {
        callback();
      }
    };

    const validateRegisterUsername = async (rule, value, callback) => {
      if (this.isRegister) {
        try {
          // 等待异步请求完成
          const exists = await PostRequest("/check-username", value);
          if (exists) {
            this.canRegister = false;
            callback(new Error("该用户名已被注册"));
          } else {
            this.canRegister = true;
            console.log('该用户名未被注册');
            callback();
          }
        } catch (error) {
          console.error("验证用户名时发生错误:", error);
          callback(new Error("验证用户名时发生错误"));
        }
      } else {
        callback();
          }
    };

    const validateConfirmPassword = (rule, value, callback) => {
      if (value !== this.registerForm.password) {
        this.canRegister = false;
        callback(new Error("两次输入的密码不一致"));
      } else {
        this.canRegister = true;
        callback();
      }
    };

    const validateCode = async (rule, value, callback) => {
      try{
        const response = await PostRequest('/verify-code', {'email': this.registerForm.email, 'code': this.registerForm.code});
        console.log('验证码结果', response);
        if(response){
          callback();   
          this.canRegister = true;
        }else{
          callback(new Error("验证码验证失败"));
          this.$message.error("验证码验证失败");
          this.canRegister = false;
        }
        
      }catch(error){
        console.error('验证码验证失败', error);
        callback(new Error("验证码验证失败"));
        this.$message.error("验证码验证失败");
        this.canRegister = false;
      }
    };

    return {
      loginPageTitle: loginPageTitle,
      loginForm: {
        username: "",
        password: "",
      },
      loginRules: {
        username: [
          { required: true, trigger: "blur", validator: validateUsername },
        ],
        password: [
          { required: true, trigger: "blur", validator: validatePassword },
        ],
      },
      registerRules: {
        username: [
          { required: true, trigger: "blur", validator: validateRegisterUsername },
        ],
        password: [
          { required: true, trigger: "blur", validator: validatePassword },
        ],
        confirmPassword: [
          { required: true, trigger: "blur", validator: validateConfirmPassword },
        ],
        code: [
          { required: true, trigger: "blur", validator: validateCode },
        ],
      },  
      registerForm: {
        username: "",
        password: "",
        confirmPassword: "",
        email: "",
        code: ""
      },
      passwordType: "password",
      capsTooltip: false,
      loading: false,
      redirect: undefined,
      otherQuery: {},
      isRegister: false,
      canRegister: true,
    };
  },
  watch: {
    $route: {
      handler: function (route) {
        const query = route.query;
        if (query) {
          this.redirect = query.redirect;
          this.otherQuery = this.getOtherQuery(query);
        }
      },
      immediate: true,
    },
  },
  created() {
    // window.addEventListener('storage', this.afterQRScan)
  },
  mounted() {
    if (this.loginForm.username === "") {
      this.$refs.username.focus();
    } else if (this.loginForm.password === "") {
      this.$refs.password.focus();
    }
  },
  destroyed() {
    // window.removeEventListener('storage', this.afterQRScan)
  },
  methods: {
    switchRegister(){
      this.isRegister = true;
    },
    
    async sendEmail(){
      console.log('发送邮件');
      try{
        const response = await PostRequest('/send-verification-code', {'email': this.registerForm.email});
        this.$message.success('发送邮件成功');
        console.log('发送邮件成功', response);
      }catch(error){
        console.error('发送邮件失败', error);
        this.$message.error('发送邮件失败');
      }
    },
    switchLogin() {
      this.isRegister = false;
    },  
    async handleRegister() {
      this.isRegister = true;
      if(!this.canRegister){
        alert('注册信息填写错误！');
      }else{
        console.log('注册信息', this.registerForm);
        const response = await PostRequest('/register', 
          {
            username: this.registerForm.username, 
            password: this.registerForm.password,
            email: this.registerForm.email,
          }
        );
        if(response){
          this.$message.success('注册成功'); 
        }else{
          this.$message.error('注册失败');
        }
            
        
      }
    },
    checkCapslock(e) {
      const { key } = e;
      this.capsTooltip = key && key.length === 1 && key >= "A" && key <= "Z";
    },
    showPwd() {
      if (this.passwordType === "password") {
        this.passwordType = "";
      } else {
        this.passwordType = "password";
      }
      this.$nextTick(() => {
        this.$refs.password.focus();
      });
    },
    handleLogin() {
      login(this.loginForm.username, this.loginForm.password)
        .then((response) => {
          saveToken(response.data, this.loginForm.username);
          this.$router.push("/");
        })
        .catch((error) => {
          console.error("Login failed:", error);
        });
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== "redirect") {
          acc[cur] = query[cur];
        }
        return acc;
      }, {});
    },
  },
};
</script>

<style lang="scss" scoped>
.login-page {
  background-image: url("@/assets/images/login_background.png");
  position: absolute;
  display: flex;
  flex-direction: column;
  justify-content: center; /* 上下居中 */
  align-items: center; /* 水平居中 */
  height: 100vh;
  width: 100%;
  margin: -10px -10px -10px;

  .login-container {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 750px;
    height: 400px;
    box-shadow: 0px 2px 20px rgba(18, 91, 215, 0.22);
    border-radius: 10px;
  }

  .intro-panel {
    width: 420px;
    background: url("@/assets/images/login.png") no-repeat center/cover;

    .app-name {
      display: flex;
      align-items: center;
      margin: 56px 42px;
    }

    .line {
      height: 1px;
      background: linear-gradient(
        90deg,
        rgba(255, 255, 255, 0) 0%,
        rgba(255, 255, 255, 1) 100%
      );
    }
  }

  .login-panel {
    flex: 1;
    padding: 30px;
    border-radius: 0px 10px 10px 0px;

    .login-form {
      display: flex;
      flex-direction: column; /* 垂直排列子元素 */
      align-items: center; /* 水平居中 */
      justify-content: center; /* 垂直居中 */
      .title-container {
        text-align: center;
        color: rgb(255, 255, 255);

        .title {
          font-size: 26px;
          font-weight: bold;
          font-family: Cera-Bold, sans-serif;
          margin-bottom: 20px;
        }
      }

      .el-input {
        margin-bottom: 20px;
      }

      .show-pwd {
        position: absolute;
        right: 10px;
        top: 7px;
        cursor: pointer;
      }

      .login-btn {
        width: 50%;
        color: rgb(255, 255, 255);
        font-size: 20px;
        font-family: Cera-Bold, sans-serif;
        height: 52px;
        background: rgba(0, 0, 0, 0)
          linear-gradient(
            60deg,
            rgb(247, 149, 51),
            rgb(243, 112, 85),
            rgb(239, 78, 123),
            rgb(161, 102, 171),
            rgb(80, 115, 184),
            rgb(16, 152, 173),
            rgb(7, 179, 155),
            rgb(111, 186, 130)
          )
          repeat scroll 0% 0% / 300% 300% padding-box border-box;
        padding: 16px 12px;
        border-radius: 6px;
        transform: matrix(1, 0, 0, 1, 0, 0);
        line-height: 20px;
        display: flex;
        align-items: center;
        justify-content: center;
        text-align: center;
      }
    }
  }

  .footer {
    position: absolute;
    bottom: 10px;
    left: 0;
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 12px;
    color: rgb(255, 255, 255);
  }

  .svg-container {
    display: flex; /* 设置为 flex 布局 */
    align-items: center; /* 垂直方向居中对齐 */
    gap: 8px; /* 设置图标和输入框之间的间距 */
    width: 100%; /* 保证容器宽度适应 */
    background-color: transparent; /* 确保初始背景透明 */
  }

  .svg-container:hover {
    background-color: transparent; /* 阻止 hover 时的背景色变化 */
  }

  .el-icon-user,
  .el-icon-mobile {
    font-size: 20px; /* 设置图标大小 */
  }

  .el-input {
    flex: 1; /* 输入框占据剩余空间 */
  }

  .el-menu-item {
    width: 100%;
    background-color: transparent; /* 确保初始背景透明 */
  }

  .el-menu-item:hover {
    background-color: transparent; /* 阻止 hover 时的背景色变化 */
  }

  .show-pwd {
    font-size: 20px;
    color: #889aa4;
    cursor: pointer;
  }

}
</style>
